<template>
    <section class="bimviewersection" >
  <div id="view" style="position: relative;">
    <div id="labels"></div>
    <div id="northarrow"></div>
    <div id="data-gui-container"></div>
</div>

<!-- popup -->
<div id="popup">
  <div id="closebtn">&times;</div>
  <div id="popupbar"></div>
  <div id="popupbody">
    <div id="popupcontent"></div>

    <!-- query result -->
    <div id="queryresult">
      <table id="qr_layername_table">
        <caption>图层</caption>
        <tr><td id="qr_layername"></td></tr>
      </table>

      <table id="qr_coords_table">
        <caption>坐标</caption>
        <tr><td id="qr_coords"></td></tr>
      </table>
      <table id="monitor_table" v-if="monitorProVisible">
        <caption>实时监测</caption>
        <tr><td>时间</td><td>{{monitorDate}}</td></tr>
        <tr><td>监测值</td><td>{{monitorData}}</td></tr>
      </table>
      <!-- attributes -->
      <table id="qr_attrs_table">
        <caption>属性</caption>
      </table>
      <table>
        <caption>操作</caption>
        <div class="action-btn action-zoom" @click="zoomin">缩放到</div>
        <div class="action-btn action-move" @click="move">移动</div>
        <div class="action-btn action-orbit" @click="orbit">旋转</div>
      </table>
    </div>

    <!-- page info -->
    <div id="pageinfo">

      <h1>当前视图URL</h1>
      <div><input id="urlbox" type="text"></div>

      <h1>用法</h1>
      <table id="usage">
        <tr><td colspan="2" class="star">鼠标</td></tr>
        <tr><td>左键 + 移动</td><td>旋转</td></tr>
        <tr><td>滚轮</td><td>缩放</td></tr>
        <tr><td>左键 + 移动</td><td>平移</td></tr>

        <tr><td colspan="2" class="star">键盘</td></tr>
        <tr><td>方向键</td><td>水平移动</td></tr>
        <tr><td>Shift + 方向键</td><td>转动</td></tr>
        <tr><td>Ctrl + 方向键</td><td>旋转</td></tr>
        <tr><td>Shift + Ctrl + Up / Down</td><td>放大/缩小</td></tr>
        <tr><td>L</td><td>切换标签显示</td></tr>
        <tr><td>R</td><td>开始 / 停止 旋转动画</td></tr>
        <tr><td>W</td><td>线框模式</td></tr>
        <tr><td>Shift + R</td><td>重置相机位置</td></tr>
        <tr><td>Shift + S</td><td>保存图片</td></tr>
      </table>
    </div>
  </div>
</div>

<!-- progress bar -->
<div id="progress"><div id="bar"></div></div>

<!-- footer -->
<div id="footer"></div>
    </section>
</template>

<script>
  //import { heightMap } from './js/heatmap'
export default {
    data(){
        return{
            monitorProVisible: false,
            monitorPointId: 180,
            monitorDate:"",
            monitorData:"",
            app: null,
            hmap:null,
            texsize: 512,
            heatradus_s:1,
            heatradus_e:3,
            heightRatio:1,
            projectId:0,
            hdata:[
                [453091.20, 4425182.98, 20.00],
                [453097.41, 4425177.64, 20.00],
                [453101.85, 4425173.77, 12.00],
                [453105.46, 4425170.49, 12.000],
                [453133.19, 4425146.98, 12.82],
                [453137.53, 4425143.18, 4.88],
                [453144.97, 4425136.76, 61.82],
                [453099.99, 4425146.30, 2.00],
                [453087.87, 4425155.67, 2.00],
                [453116.72, 4425132.60, 2.00],
                [453107.49, 4425140.18, 2.00],
                [453120.48, 4425120.70, 2.00],
                [453109.94, 4425129.37, 2.00],
                [453109.94, 4425129.37, 2.00],
                [453103.57, 4425134.32, 2.00],
                [453094.95, 4425141.30, 2.00],
                [453082.81, 4425149.98, 2.00],
                [453078.09, 4425154.93, 2.00],
                [453071.79, 4425160.13, 2.00],
                [453077.07, 4425143.33, 2.00],
                [453087.42, 4425133.68, 2.00],
                [453093.64, 4425128.13, 2.00],
                [453093.64, 4425128.13, 2.00],
                [453100.60, 4425122.47, 2.00],
                [453107.26, 4425116.81, 2.00],
                [453111.79, 4425112.81, 2.00],
                [453150.47, 4425158.67, 2.00],
                [453146.19, 4425162.26, 2.00],
                [453115.71, 4425188.31, 2.00]
            ],
            // heightMap:function () {
            //     return heightMap();
            // },
            // heatFragment:function () {
            //     return hmap.heatFragment();
            // },
            // heatVertex:function () {
            //     return hmap.heatVertex();
            // }
        }
    },
  mounted() {
    // if (typeof proj4 === "undefined")
    //   document.getElementById("lib_proj4js").style.display = "none";
      var _this = this;
     _this.app = Q3D.application;
     var app = _this.app;
     var container = document.getElementById("view");

    app.init(container); // initialize application
      // 触发事件    add  by zoom
    _this.app.renderer.domElement.addEventListener("mouseup",this.activeMonitorItem);
    // when all objects have been loaded
    app.addEventListener("sceneLoaded", function() {
      // set custom plane z range
      var box = new THREE.Box3().setFromObject(app.scene),
        zMin = app.scene.toMapCoordinates(0, 0, box.min.y).z,
        zMax = app.scene.toMapCoordinates(0, 0, box.max.y).z;
      Q3D.gui.initCustomPlaneFolder(zMin, zMax);
    });
    // load the scene
    if(this.$route.query.projectId != undefined)
        _this.projectId = this.$route.query.projectId;
    var path = "./libs/data/index"+ String(_this.projectId)+"/scene.json";
     // var path = "./libs/data/index"+"/scene.json";
    //console.log("dsadfasdf",path,_this.projectId, this.$route.query.project);
    app.loadJSONFile(path, function() {
        app.start();
        _this.makeHeatMap();
        var tgui = Q3D.gui.init();
        var cjlayer = tgui.addFolder('沉降热图');
        var changeHmapVisible = function (value) {  _this.changeHmapVisible(value);};
        var changeHeightRatios = function (value) {  _this.changeHeightRatios(value);};
        var reMakeHeatmap = function () {_this.makeHeatMap();};
        cjlayer.add(_this, "heightRatio", 0.1, 4).name("比例").onChange(changeHeightRatios);
        cjlayer.add( _this.hmap, 'visible').name('显示').onChange(changeHmapVisible);
        cjlayer.add( _this, 'heatradus_s', 0, 5).name('开始半径');
        cjlayer.add( _this, 'heatradus_e', 0, 10).name('结束半径');
        cjlayer.add( _this, 'texsize', 128, 1024).name('热点大小');
        cjlayer.add( _this, 'makeHeatMap');
      // North arrow inset
      if (Q3D.Config.northArrow.visible)
        app.buildNorthArrow(
          document.getElementById("northarrow"),
          app.scene.userData.rotation
        );
        //var text = new datGUI();
        //tgui.remember(Q3D.gui.parameters);
    });
  },
  methods:{
      zoomin(){
          this.app.cameraAction.zoomIn();
          this.app.closePopup();},
      move(){
          this.app.cameraAction.move();
          this.app.closePopup();},
      orbit(){
          this.app.cameraAction.orbit();
          this.app.closePopup();},
      homeView(){
        this.app.controls.reset();
      },
      activeMonitorItem()
      {
          this.monitorProVisible = false;
          if(this.app.selectedObject !==null &&this.app.selectedObject.userData!== null)
          {
              var _layerId = this.app.selectedObject.userData.layerId;
              var layer = this.app.scene.mapLayers[_layerId];
              var pid = 1;
              var mtype = "";
              for (var i = 0, l = layer.properties.propertyNames.length; i < l; i++) {
                  if(layer.properties.propertyNames[i] === "id"||layer.properties.propertyNames[i] === "ID")
                      pid = this.app.selectedObject.userData.properties[i];
                  if(layer.properties.propertyNames[i] === "type")
                      mtype = this.app.selectedObject.userData.properties[i];
              }
              if(mtype == "5_jrx"||mtype == "14-hdm"||mtype=="15-zdm")
              {
                  this.$emit("profileIdChange",pid);
              }
              if(mtype == "zzyw"||mtype == "")
              {
                  this.monitorProVisible = true;
                  this.monitorPointId = pid;
                  this.$emit("monitorIdChange",pid);
                  //alert(pid);
              }
          }
      },
      emitKzMessage(){
          this.$emit("zkIdChange",this.kzbId);
          this.app.closePopup();

      },
      SelectChange(){
          this.app.isSelected = !this.app.isSelected;
      },
      changeMonitorItemVisibility(monitorId,visibleflag){
          var _this = this;
          var objs =  _this.app.scene.queryableObjects();
          objs.forEach(function (obj) {
              if(_this.isOwnEmpty(obj.userData))
                  return;
           var _layerId = obj.userData.layerId;
           var layer = _this.app.scene.mapLayers[_layerId];
           var pid = 1;
           var mtype = "";
           if(layer.type != "point"&&layer.type != "polygon"&&layer.type != "line"||layer.properties.propertyNames==undefined) return;
           for (var i = 0, l = layer.properties.propertyNames.length; i < l; i++) {
               if(layer.properties.propertyNames[i] == "id"||layer.properties.propertyNames[i] == "ID")
               {
                   pid = obj.userData.properties[i];
                   if(pid == monitorId)
                   {
                       obj.visible = visibleflag;
                       _this.app.scene.updateMatrixWorld();
                       _this.app.render(true);
                       break;
                   }
               }
           }
       })
      },
      isOwnEmpty(obj)
      {
          for(var name in obj)
          {
              if(obj.hasOwnProperty(name))
              {
                  return false;//返回false，不为空对象
              }
          }
          return true;//返回true，为空对象
      },
      updateScene(id){
          //this.mounted();
          this.$router.push({
              path: '/bim',
              name: 'BIM ',
              query:{
                  id: id
              }
          });
          this.$router.go(0);
      },
      makeHeatMap(){
          var _this = this;
          var box = new THREE.Box3().setFromObject(_this.app.scene);
          this.app.scene.remove(this.hmap);
          this.hmap = null;
          var heatVertex = `
        uniform sampler2D heightMap;
        uniform float heightRatio;
        varying vec2 vUv;
        varying float hValue;
        void main() {
          vUv = uv;
          vec3 pos = position;
          hValue = texture2D(heightMap, vUv).r;
          pos.y = hValue * heightRatio;
          gl_Position = projectionMatrix * modelViewMatrix * vec4(pos,1.0);
        }
      `;
          var heatFragment = `
        varying float hValue;

        // honestly stolen from https://www.shadertoy.com/view/4dsSzr
        vec3 heatmapGradient(float t) {
          return clamp((pow(t, 1.5) * 0.8 + 0.2) * vec3(smoothstep(0.0, 0.35, t) + t * 0.5, smoothstep(0.5, 1.0, t), max(1.0 - t * 1.7, t * 7.0 - 6.0)), 0.0, 1.0);
        }

        void main() {
          float v = abs(hValue - 1.);
          gl_FragColor = vec4(heatmapGradient(hValue), 1. - v * v) ;
        }
      `;
          var xmin = _this.app.scene.toMapCoordinates(box.min.x, 0, 0).x;
          var xmax = _this.app.scene.toMapCoordinates(box.max.x, 0, 0).x;
          var ymin = _this.app.scene.toMapCoordinates(0, box.min.z, 0).y;
          var ymax = _this.app.scene.toMapCoordinates(0, box.max.z,  0).y;
          //console.log(xmin,xmax,ymin,ymax);
          var heightMap = createHeightMap();
          //console.log(heightMap);

          function createHeightMap(){
              var canvas = document.createElement("canvas");
              canvas.width = _this.texsize;
              canvas.height = _this.texsize;
              var ctx = canvas.getContext("2d");
              ctx.fillStyle = "black";
              ctx.fillRect(0, 0, _this.texsize, _this.texsize);
              for(let i = 0; i < _this.hdata.length; i++){
                 //  var x =  Math.floor((453038 - xmin)/(xmax - xmin)*255);
                 //  var y = Math.floor(( ymax - 4425075)/(ymax - ymin)*255);//4859865.761349644
                   var x =  Math.floor((_this.hdata[i][0] - xmin)/(xmax - xmin)*(_this.texsize-1));
                  //console.log(_this.hdata[i][1]);
                   var y = Math.floor(( ymax - _this.hdata[i][1])/(ymax - ymin)*(_this.texsize-1));//4859865.761349644
                  var radius = _this.heatradus_e;
                  var grd = ctx.createRadialGradient(x, y, _this.heatradus_s, x, y, radius);
                   var h8 = Math.floor(Math.random() * 10)+205;
                  //var h8 =y;
                  grd.addColorStop(0, "rgb("+ h8 + "," + h8 + "," + h8 +")");
                  grd.addColorStop(1, "transparent");
                  ctx.fillStyle = grd;
                  ctx.fillRect(0, 0, _this.texsize, _this.texsize);
              }
              return new THREE.CanvasTexture(canvas);
          }

          //console.log(xmax-xmin, ymax-ymin);
          var pbox = new THREE.Box3().setFromObject(_this.app.scene);
          var planeGeometry = new THREE.PlaneBufferGeometry(pbox.max.x-pbox.min.x, pbox.max.z-pbox.min.z, 1000, 1000);//xmax-xmin, ymax-ymin
          planeGeometry.rotateX(-Math.PI * 0.5);

          var heat = new THREE.Mesh(planeGeometry, new THREE.ShaderMaterial({
              uniforms: {heightMap: {value: heightMap},
                  heightRatio: {value: 0.3}
              },
              vertexShader: heatVertex,
              fragmentShader: heatFragment,
              transparent: true
          }));
          heat.rotateX(Math.PI * 0.5);
          this.hmap = heat;
          this.app.scene.add(this.hmap);
          this.app.render();
      },
      //changeHeightRatios(value){this.hmap.material.uniforms.heightRatio = value; this.app.render();},
      changeHeightRatios(value){this.hmap.material.uniforms.heightRatio.value = value; this.app.render();},
      changeHmapVisible(value){this.hmap.visible = value; this.app.render();},
  }

};
</script>
<style>
  #data-gui-container{
    position: absolute;
    right: -15px;
    top: -70px;
    text-align: left;
    }
    /*#popup{*/
    /*margin-left: 210px;*/
    /*}*/
    .bimviewersection{
        position: absolute;
    }
</style>
